﻿// ***********************************************************************
// Assembly         : OSS.BIM
// Author           : tian_
// Created          : 09-05-2018
//
// Last Modified By : tian_
// Last Modified On : 09-05-2018
// ***********************************************************************
// <copyright file="PropertiesGridControl.cs" company="北京智帆高科科技有限公司">
//     Copyright © 北京智帆高科科技有限公司 2018
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using OSS.BIM.Business;
using OSS.BIM.Business.Utility;
using OSS.BIM.Commands.PropertyCmds;
using OSS.BIM.Model;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using ZFGK.Addins;
using ZFGK.DevExprss.Utility;
using ZFGK.Utility;

namespace OSS.BIM.UI.Controls
{
    /// <summary>
    /// 
    /// </summary>
    public partial class PropertiesGridControl : XtraUserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PropertiesGridControl"/> class.
        /// </summary>
        public PropertiesGridControl()
        {
            InitializeComponent();

            colName.FieldName = "DiaplayLable";
            colVal.FieldName = "Value";
            gridView.CustomDrawRowIndicator += delegate(object sender, RowIndicatorCustomDrawEventArgs e)
            {
                if (e.Info.IsRowIndicator && e.RowHandle > -1)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
            };
            Chenged = false;
        }

        /// <summary>
        /// The instance
        /// </summary>
        private static PropertiesGridControl instance = new PropertiesGridControl();

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static PropertiesGridControl Instance
        {
            get { return instance; }
        }

        /// <summary>
        /// The properties
        /// </summary>
        public List<ModelProperty> properties = null;

        /// <summary>
        /// 
        /// </summary>
        public List<ModelProperty> Properties
        {
            get { return properties; }
        }

        /// <summary>
        /// Sets the properties.
        /// </summary>
        /// <param name="properties">The properties.</param>
        public void SetProperties(List<ModelProperty> properties)
        {
            gridControl.DataSource = null;
            this.properties = null;
            try
            {
                this.properties = properties;
                gridControl.DataSource = properties;
            }
            catch
            {
            }
        }

    /// <summary>
        /// The model information
        /// </summary>
        private ModelElement modelElement = null;

        /// <summary>
        /// Gets or sets the model information.
        /// </summary>
        /// <value>The model information.</value>
        public ModelElement ModelElement
        {
            get { return modelElement; }
            set
            {
                if (Instance.Chenged && XtraMessageBox.Show("属性已经更改，是否保存？", "提醒", MessageBoxButtons.OKCancel) ==
                    DialogResult.OK)
                {
                    Save();
                }

                modelElement = value;
                Chenged = false;
                if (modelElement != null)
                {
                    SetProperties(modelElement.GetProperties().ToList());
                }
            }
        }

        /// <summary>
        /// Gets or sets the popup menu.
        /// </summary>
        /// <value>The popup menu.</value>
        public PopupMenu PopupMenu { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="PropertiesGridControl"/> is chenged.
        /// </summary>
        /// <value><c>true</c> if chenged; otherwise, <c>false</c>.</value>
        public bool Chenged { get; set; }

        /// <summary>
        /// Handles the MouseClick event of the dgvModel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private void dgvModel_MouseClick(object sender, MouseEventArgs args)
        {
            if (PopupMenu == null || modelElement == null)
                return;

            if (args.Button == MouseButtons.Right)
            {
                PopupMenu.ItemLinks.Clear();
                PopupMenu.NewButton("添加", btn => btn.Tag = (typeof(PropertyAddCmd)));

                GridHitInfo gridHitInfo = gridView.CalcHitInfo(new Point(args.X, args.Y));
                object row = gridHitInfo.RowHandle > 0 ? gridView.GetRow(gridHitInfo.RowHandle) : null;

                if (row != null)
                {
                    PopupMenu
                        .NewButton("编辑", btn => btn.Tag = (new CmdInfo(typeof(PropertyEditCmd), row)))
                        .NewButton("删除", btn => btn.Tag = (new CmdInfo(typeof(PropertyDeleteCmd), row)));
                }

                if (Chenged)
                {
                    PopupMenu.NewButton("保存", true, btn => btn.Tag = (typeof(PropertySaveCmd))); 
                }

                if (PopupMenu.ItemLinks.Count > 0)
                {
                    PopupMenu.ShowPopup(Control.MousePosition);
                }
            }
        }

        public static void Save()
        {
            try
            {
                if (Instance.Chenged)
                {
                    var modelElement = ModelElementDbUtil.GetAt(Instance.ModelElement.ModelElementId);

                    var olds = Instance.Properties.Where(d => d.ModelElementId > 0).ToArray();
                    var news = Instance.Properties.Where(d => d.ModelElementId == 0).ToArray();
                    // 删除
                    var ids = olds.Select(d => d.ModelElementId).ToArray();
                    DB.Context.Delete<ModelProperty>(d =>
                        d.ModelElementId == modelElement.ModelElementId && !d.ModelElementId.In(ids));
                    // 更新
                    ModelPropertyDbUtil.Update(olds);
                    // 添加
                    foreach (var modelProperty in news)
                    {
                        modelProperty.ModelElementId = modelElement.ModelElementId;
                    }
                    ModelPropertyDbUtil.Insert(news);

                    Instance.Chenged = false;
                    ZfMessageUtil.ShowAlert("保存属性成功！");
                }
            }
            catch (Exception e)
            {
                ZfMessageUtil.ShowError(e.GetAllExMessage());
            }
        }
    }
}
